package net.notdot.aeauth;

import java.util.Calendar;
import java.util.GregorianCalendar;

import android.accounts.Account;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.ViewDebug.FlagToString;
import android.widget.Toast;

public class AndroidAlarmService extends Service {

	private PendingIntent pendingIntent;

	 /** Called when the activity is first created. */
	 public void onCreate() {
	     super.onCreate();
	 }
	 
	 @Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		 
		 Log.i("AndroidAlarmService","onStart");
	
		 Bundle b = new Bundle();
		 b=intent.getExtras();
		 ListaAvisos avisos=b.getParcelable("avisos");
		 Account account=b.getParcelable("passingaccount");
		 Log.i("AndroidAlarmService","account: "+account.name);
	     if(avisos==null) {Log.i("onStart","avisos = null");}
	     Log.i("AndroidAlarmService","onStart avisos");

	     for(Aviso a : avisos)
	     {
			     if(a.getRepeticion().compareTo("on")!=0)
			     {    //si es una alarma no repetitiva
			    	 for(int i=0;i<a.getCuando().size();i++)
			    	 {
				    	 Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
				    	 Bundle ba = new Bundle();
				    	 ba.putString("actividad", a.getActividad());
				    	 ba.putString("cuando", a.getCuando().get(i));
				    	 ba.putString("fecha",a.getFecha());
				    	 Log.i("AndroidAlarmService","actividad: "+a.getActividad());
				    	 Log.i("AndroidAlarmService","cuando: "+a.getCuando().get(i));
				    	 Log.i("AndroidAlarmService","fecha: "+a.getFecha());
				    	 
				    	 int primerabarra= a.getFecha().indexOf("/");
				    	 int day_of_month=Integer.valueOf(a.getFecha().substring(0,primerabarra));// de fecha los caracteres hasta el primer '/'
				    	 Log.i("day of month",String.valueOf(day_of_month));
				    	 int segundabarra=a.getFecha().indexOf("/", primerabarra+1);
				    	 int month=Integer.valueOf(a.getFecha().substring(primerabarra+1,segundabarra));  // desde el primer '/' al siguiente '/'
				    	 Log.i("month",String.valueOf(month));
				    	 
				    	 ba.putParcelable("passingaccount", account);
				    	 myIntent.putExtras(ba);
				    	 int intent_id=(int) System.currentTimeMillis();
				    	 Log.i("AndroidAlarmService","request code: "+intent_id);
					     pendingIntent = PendingIntent.getService(AndroidAlarmService.this, intent_id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
					            
					            Calendar cur_cal = new GregorianCalendar();
					            cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar
					            
					            Calendar cal = new GregorianCalendar();
					            cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
					            cal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(a.getCuando().get(i)));
					            cal.set(Calendar.MINUTE, 0);
					            cal.set(Calendar.SECOND, 0);
					            cal.set(Calendar.MILLISECOND, 0);
					            cal.set(Calendar.DATE, day_of_month);
					            Log.i("Cur_cal","DATE: "+cur_cal.get(Calendar.DATE));
					            cal.set(Calendar.MONTH, month-1);
					            Log.i("Cur_cal","MONTH: "+cur_cal.get(Calendar.MONTH));
					            
					      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
					      alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
					     Log.i("AndroidAlarmService","alarmManager.set()");    
				   
			    	 }
			     }
			     else if(a.getRepeticion().compareTo("on")==0)
			     {
			    	 for(int i=0;i<a.getCuando().size();i++)
			    	 {
			    		 Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
				    	 Bundle ba = new Bundle();
				    	 ba.putString("actividad", a.getActividad());
				    	 ba.putString("cuando", a.getCuando().get(i));
				    	 ba.putString("fecha",a.getFecha());
				    	 Log.i("AndroidAlarmService","actividadR: "+a.getActividad());
				    	 Log.i("AndroidAlarmService","cuandoR: "+a.getCuando().get(i));
				    	 Log.i("AndroidAlarmService","fechaR: "+a.getFecha());
				    	 ba.putParcelable("passingaccount", account);
				   				    	 
				    	 myIntent.putExtras(ba);
						 int interval=24*60*60*1000; //24 horas * 60 min * 60 seg * 1000. Cada 24 horas se repite la alarma.
				    	 int intent_id= (int)System.currentTimeMillis();
				    	 Log.i("AndroidAlarmService","request code: "+intent_id);
				    	 pendingIntent = PendingIntent.getService(AndroidAlarmService.this, intent_id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
				         
				            Calendar cur_cal = new GregorianCalendar();
				            cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar
				            Calendar cal = new GregorianCalendar();
				            cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
				            cal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(a.getCuando().get(i)));
				            cal.set(Calendar.MINUTE, 0);
				            cal.set(Calendar.SECOND, 0);
				            cal.set(Calendar.MILLISECOND, 0);
				            cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
				            cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
				    	 
				    	 AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);				         		
					     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), interval, pendingIntent);
					     Log.i("AndroidAlarmService","alarmManager.setRepeating()");
			    	 }
			     }
	    	 }
		 Log.i("AndroidAlarmService","stopAndroidAlarmService");
	     stopSelf();
}
	 
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		Toast.makeText(AndroidAlarmService.this, "AndroidAlarmService.onStop", Toast.LENGTH_LONG).show();
		
	}
}
